package com.eduService.Service.ServiceImpl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyuncs.exceptions.ClientException;
import com.eduService.Service.ossService;
import com.eduService.utils.ConstantProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class ossServiceImpl implements ossService {
    @Override
    public String uploadFile(MultipartFile file) {
        OSS ossClient = new OSSClientBuilder().build("oss-accelerate.aliyuncs.com", "LTAI5tB7GDKsmFyWKDAQGotv", "vjqvRGX16j9QkW7Zx7JXTqHIgd1yzw");
        try {
            InputStream inputStream = file.getInputStream();
            // 创建PutObject请求。
            //对文件名做唯一性的修改，防止名字相同，头像会被覆盖
           String filename = "headimages/"+ UUID.randomUUID().toString().replaceAll("-","")+ file.getOriginalFilename();
            System.out.println(filename);
            ossClient.putObject("fengmangbucket", filename, inputStream);
            // 拼接路径并返回
            // https://fengmangbucket.oss-cn-guangzhou.aliyuncs.com/image1.jpg
//            https://fengmangbucket.oss-cn-guangzhou-internal.aliyuncs.com/image1.jpg
            String url = "https://"+ConstantProperties.BUCKET_NAME+".oss-cn-guangzhou.aliyuncs.com/"+filename;
            return url;
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
        }
        return null;
    }
}
